package com.lepu.app.fun.hospital;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.bean.BeanCollectKnowledge;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class HospitalConsultDetailActivity extends BaseFragmentActivity
		implements OnTopbarNewLeftLayoutListener ,AsyncRequest{

	private static final String REQUEST_SHARE = "request_share";
	
	private CustomTopBarNew mTopbar;
	String mTitle;
	String mAnswer;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hospital_consult_detail_activity);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("问题详情");
		mTopbar.setonTopbarNewLeftLayoutListener(this);

		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
			TextView answerTextView = (TextView) findViewById(R.id.answerTextView);

			mTitle = data.getString("question");
			mAnswer = data.getString("answer");

			questionTextView.setText(mTitle);
			answerTextView.setText(mAnswer);
		}
		
		addTopBarRight();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/*
	 * topbar right
	 */
	@SuppressLint("InflateParams")
	private void addTopBarRight() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.app_topbar_right_content, null);
		ImageButton collectImageButton = (ImageButton) view
				.findViewById(R.id.rightImageButton1);
		ImageButton shareImageButton = (ImageButton) view
				.findViewById(R.id.rightImageButton2);
		
		collectImageButton.setBackgroundResource(R.drawable.icon_fav_no);
		shareImageButton.setBackgroundResource(R.drawable.icon_share);

		collectImageButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				clickCollect();
			}
		});

		shareImageButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				clickShare();
			}
		});
		mTopbar.addRightContentLayout(view);

		// update collect
		updateCollectState();
	}

	private void updateCollectState() {

		ImageButton collectImageButton = (ImageButton) findViewById(R.id.rightImageButton1);

		String uid = "-1";
		if (MyApplication.getInstance().checkIsLogin()) {
			uid = MyApplication.getInstance().getLoginInfo().UserID;
		}

		boolean flag = BeanCollectKnowledge.checkCollectItemQuestion(uid,
				mTitle);
		if (flag) {
			collectImageButton.setBackgroundResource(R.drawable.icon_fav_yes);
		} else {
			collectImageButton.setBackgroundResource(R.drawable.icon_fav_no);
		}
	}

	private void clickCollect() {
		
		boolean flagLogin = MainTabActivity.jumpLogin(this);
		
		if(flagLogin){
			return;
		}
		
		String uid = "-1";
		if (MyApplication.getInstance().checkIsLogin()) {
			uid = MyApplication.getInstance().getLoginInfo().UserID;
		}

		boolean flag = BeanCollectKnowledge.checkCollectItemQuestion(uid,
				mTitle);

		boolean updateFlag = false;
		if (flag) {
			updateFlag = BeanCollectKnowledge.deleteItemQuestion(uid, mTitle);
			
			UIHelper.showToast(this, R.string.collect_cancel);
		} else {
			BeanCollectKnowledge item = new BeanCollectKnowledge();
			item.Uid = uid;
			item.Time = System.currentTimeMillis();

			item.Type = BeanCollectKnowledge.TYPE_QUESTION;
			item.Title = mTitle;
			item.SubTitle = mAnswer;
			updateFlag = BeanCollectKnowledge.insertCollectItem(item);
			
			UIHelper.showToast(this, R.string.collect_success);
		}

		if (updateFlag) {
			updateCollectState();
		}
	}
	
	private void clickShare()
	{
		String appShareTitle = String.format("[分享自：%s app]",getResources().getString(R.string.app_name));

		StringBuffer sb = new StringBuffer();
		sb.append("问题："+mTitle);
		sb.append("\n\r");
		sb.append("答案："+mAnswer);

		String imgPath = SdLocal.getAppIconPath(getApplicationContext());
		
		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(HospitalConsultDetailActivity.this, appShareTitle, sb.toString(),
				imgPath,Setting.getAppOfficialUrl(), true, new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);
						LogUtilBase.LogD(null, "回调成功 callBackSuccess");

						requestShare();
					}

					@Override
					public void callBackFail(Object obj) {
						super.callBackFail(obj);
						LogUtilBase.LogD(null, "回调成功 callBackFail");
					}
				});
	}
	
	private void requestShare() {

		if (!MyApplication.getInstance().checkIsLogin()) {
			return;
		}

		String url = Setting.getShareSuccessUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("ObjectType", 8);//video
			params.put("ObjectID", -1);//readUrlArray[readId]
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(url, map, null, this, REQUEST_SHARE,false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_SHARE)) {
			LogUtilBase.LogD(null, "share video success");
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				int integral = dataObject.optInt("ChangeCredits");
				LoginUtil.jumpIntegral(HospitalConsultDetailActivity.this, integral);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		// TODO Auto-generated method stub
		
	}

}
